package com.atguigu.auth.controller;

import com.atguigu.auth.handler.GuiguException;
import com.atguigu.auth.jwt.JwtHelper;
import com.atguigu.auth.result.Result;
import com.atguigu.auth.service.SysMenuService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.auth.utils.MD5;
import com.atguigu.model.system.SysUser;
import com.atguigu.vo.system.LoginVo;
import com.atguigu.vo.system.RouterVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 赵星
 * @version 1.0
 * @Date 2023/10/12 16:53
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
@Slf4j
public class IndexController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;


    @ApiOperation("登入")
    @PostMapping("/login")
    public Result login (@RequestBody LoginVo loginVo) {
        //{"code":200,"data":{"token":"admin-token"}}
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", "admin-token");
        //获取用户名是否存在
        String username = loginVo.getUsername();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserService.getOne(wrapper);
        if (StringUtils.isEmpty(sysUser)) {
            throw new GuiguException(201, "用户名不存在");
        }
        //获取密码是否正确
        String password_input = MD5.encrypt(loginVo.getPassword());//用户输入的密码
        String password_db = sysUser.getPassword();//数据库存储的密码
        if (!password_db.equals(password_input)) {
            throw new GuiguException(201, "密码错误");
        }
        //获取状态是否可用
        if (sysUser.getStatus() != 1) {
            throw new GuiguException(201, "当前用户不可用");
        }

        //创建token
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result info (HttpServletRequest request) {
        //{code: 200, data: {roles: ["admin"], introduction: "I am a super administrator",…}}
        //从请求头获取用户信息（token字符串）
        String token = request.getHeader("token");
        //从token字符串中获取用户id或者名称
        Long userId = JwtHelper.getUserId(token);
        //根据用户id查询数据库，把用户信息获取出来
        SysUser sysUser = sysUserService.getById(userId);
        //根据用户id获取用户可以操作的菜单列表
        //动态构建路由结构，进行显示
        List<RouterVo> routerVoList =  sysMenuService.finUserMenuListByUserId(userId);
        //根据用户id获取用户可以操作的按钮列表
        List<String> perList = sysMenuService.findUserPermsList(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("roles", "['admin']");
        map.put("introduction", "I am a super administrator");
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name", sysUser.getUsername());
        map.put("buttons", perList);
        map.put("routers", routerVoList);
        return Result.ok(map);
    }
    @ApiOperation("退出登入")
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }
}
